<template>
  <div>
    <TopFilter ref="topFilter" :list="topFilterList" @filterChange="handleSearch" @onCollapse="collapseHandle" :cols="4"></TopFilter>
    <FilterTable
      ref="table"
      columnsRef="allocationInRef"
      selectionType="single"
      :columns="columns"
      :fetchapi="fetchapi"
      :params="fetchParams"
      :datakey="'rows'"
      :onSyncTableData="handleSyncTableData"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="changeSelectList"
    >
      <template slot="controls">
        <el-button size="small" type="primary" @click="subAllcation">提交</el-button>
        <el-button size="small" type="primary" @click="subDeleteAllcation">作废申请</el-button>
        <el-button size="small" type="primary" @click="cancelSubDeleteAllcation">作废申请取消</el-button>
        <el-button size="small" type="primary" @click="newAllcation">新建</el-button>
        <el-button size="small" type="primary" @click="inAllcation">入库</el-button>
        <el-button size="small" type="primary" @click="handleDayin">打印</el-button>
        <el-button size="small" type="primary" @click="deleteAllcation">作废</el-button>
      </template>
    </FilterTable>
    <div v-if="dy">
      <BasePrint ref="allInprint" :data="allInprintList" template="templatepartAllocateIn" />
    </div>
    <BaseDialog title="新建调拨入库单" :visible.sync="visible" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <newAllcation @close="visible = false" @confirm="confirm" />
    </BaseDialog>
    <BaseDialog title="调拨入库单详情" :visible.sync="visible1" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <showItems @close="visible1 = false" :data="itemsData" />
    </BaseDialog>
    <BaseDialog title="调拨入库单编辑" :visible.sync="visible2" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <editItems @close="visible2 = false" :data="itemsData1" @confirm="confirm" />
    </BaseDialog>
    <BaseDialog title="审核历史" :visible.sync="showPanel2" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <showExaminedLog @close="showPanel2 = false" :data="logData" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { confirmAction, notifyAction, jsonToHump } from '@/utils';
import {
  inStorageAllocationIn,
  submitDeleteAllocationIn,
  cancelSubDeleteAllcation,
  saveAllocationIn,
  queryAllocationIn,
  queryAllocationInItems,
  deleteAllocationIn,
  submitAllocationIn,
  queryAllocationInAllItems,
  getExaminedLogs,
  dealerInfoByAllInfo,
  printData
} from '@/api/part/allocation';
import { getDealerUser } from '@/api/part/partInventory/partInventory/index.js';
import moment from 'moment';
import newAllcation from './newAllcation';
import { exportExcelFile, arrayObjDeWeight } from '@/utils/index';
import showItems from './showItems';
import editItems from './editItems';
import showExaminedLog from './showExaminedLog';

export default {
  mixins: [dictionary],
  components: {
    newAllcation,
    showItems,
    showExaminedLog,
    editItems
  },
  data() {
    return {
      topFilterList: this.createTopFIlterList(),
      columns: this.createTableColumns(),
      fetchapi: queryAllocationIn,
      statusList: this.createDictList('9031'),
      fetchParams: { xhrAbort: true },
      visible: false,
      visible1: false,
      cunUserList: [],
      dy: false,
      visible2: false,
      logData: [],
      showPanel2: false,
      itemsData: {},
      allInprintList: {},
      itemsData1: {},
      selectList: {},
      syncTableData: [] // 同步的table数据
    };
  },
  mounted() {
    console.log('statusList', this.statusList);
    this.topFilterList.find(x => x.fieldName == 'orderStatus').itemList = this.statusList;
    this.columns.find(x => x.dataIndex == 'orderStatus').dictItems = this.statusList;
    this.getAllOwnerCode();
    this.getDealerUser();
  },
  methods: {
    async getAllOwnerCode() {
      let res = await dealerInfoByAllInfo({});
      console.log(res, 'dealerInfoByAllInfo');
      let data = arrayObjDeWeight(res.data, 'dealerCode');
      this.topFilterList.find(item => item.fieldName == 'customerCode').itemList = data.map(x => ({ text: x.dealerName, value: x.dealerCode }));
    },
    async getDealerUser() {
      const res = await getDealerUser();
      this.cunUserList = res.data;
    },
    newAllcation() {
      this.visible = true;
      this.selectList = {};
    },
    changeSelectList(val) {
      if (val.length > 0) {
        this.selectList = val[0];
      }
    },
    async deleteAllcation() {
      if (Object.keys(this.selectList).length == 0) {
        this.$notify.error({ title: '提示信息', message: '请选中数据' });
        return;
      }
      if (this.selectList.orderStatus == '90311001' || this.selectList.orderStatus == '90311002' || this.selectList.orderStatus == '90311004') {
        let res = await deleteAllocationIn(this.selectList);
        if (res.resultCode == 200) {
          this.$notify({
            title: '提示',
            message: '作废成功',
            type: 'success'
          });
        }
      } else {
        this.$notify({
          title: '提示',
          message: '只有未提交、审核中和审核驳回状态可以作废',
          type: 'warning'
        });
        return;
      }
      this.selectList = {};
      this.$refs.table.DO_REFRESH();
    },
    async subAllcation() {
      if (Object.keys(this.selectList).length == 0) {
        this.$notify.error({ title: '提示信息', message: '请选中数据' });
        return;
      }
      if (this.selectList.orderStatus == '90311001' || this.selectList.orderStatus == '90311004') {
        let res = await queryAllocationInAllItems({ allocateInNo: this.selectList.allocateInNo });
        let param = _.cloneDeep(this.selectList);
        let a = res.data;
        param.allcationTable = a;
        console.log(a, 'aaaa:');
        let ros = await submitAllocationIn(param);
        if (ros.resultCode == 200) {
          this.$notify({
            title: '提示',
            message: '提交成功',
            type: 'success'
          });
          this.$refs.table.DO_REFRESH();
        }
      } else {
        this.$notify({
          title: '提示',
          message: '只有未提交、和审核驳回状态可以提交',
          type: 'warning'
        });
        return;
      }
      this.selectList = {};
    },
    async cancelSubDeleteAllcation() {
      if (Object.keys(this.selectList).length == 0) {
        this.$notify.error({ title: '提示信息', message: '请选中数据' });
        return;
      }
      if (this.selectList.orderStatus == '90311007' || this.selectList.orderStatus == '90311008') {
        let param = _.cloneDeep(this.selectList);
        let ros = await cancelSubDeleteAllcation(param);
        if (ros.resultCode == 200) {
          this.$notify({
            title: '提示',
            message: '取消成功',
            type: 'success'
          });
        }
      } else {
        this.$notify({
          title: '提示',
          message: '只有作废审核中和作废审核驳回状态可以取消',
          type: 'warning'
        });
        return;
      }
      this.selectList = {};
      this.$refs.table.DO_REFRESH();
    },
    async subDeleteAllcation() {
      if (Object.keys(this.selectList).length == 0) {
        this.$notify.error({ title: '提示信息', message: '请选中数据' });
        return;
      }
      if (this.selectList.orderStatus == '90311003' || this.selectList.orderStatus == '90311005') {
        let param = _.cloneDeep(this.selectList);
        let ros = await submitDeleteAllocationIn(param);
        if (ros.resultCode == 200) {
          this.$notify({
            title: '提示',
            message: '提交成功',
            type: 'success'
          });
        }
      } else {
        this.$notify({
          title: '提示',
          message: '只有审核通过和待入库状态可以提交作废申请',
          type: 'warning'
        });
        return;
      }
      this.selectList = {};
      this.$refs.table.DO_REFRESH();
    },
    async inAllcation() {
      if (Object.keys(this.selectList).length == 0) {
        this.$notify.error({ title: '提示信息', message: '请选中数据' });
        return;
      }
      if (this.selectList.orderStatus == '90311005') {
        let param = _.cloneDeep(this.selectList);
        let ros = await inStorageAllocationIn(param);
        if (ros.resultCode == 200) {
          this.$notify({
            title: '提示',
            message: '入库成功',
            type: 'success'
          });
        }
      } else {
        this.$notify({
          title: '提示',
          message: '只有待入库状态可以入库',
          type: 'warning'
        });
        return;
      }
      this.selectList = {};
      this.$refs.table.DO_REFRESH();
    },
    createTopFIlterList() {
      return [
        {
          type: 'INPUT',
          label: '入库单号',
          fieldName: 'allocateInNo'
        },
        {
          type: 'SELECT',
          label: '对方经销商',
          fieldName: 'customerCode',
          filterable: true,
          itemList: []
        },
        {
          type: 'RANGE_DATE',
          label: '创建日期',
          fieldName: 'createdAtBegin|createdAtEnd',
          valueFormat: 'yyyy-MM-dd'
        },
        {
          type: 'SELECT',
          label: '调拨状态',
          fieldName: 'orderStatus',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '原单据编号',
          fieldName: 'oldAllocateOutNo'
        },
        {
          type: 'RANGE_DATE',
          label: '审核日期',
          fieldName: 'examinedDateBegin|examinedDateEnd',
          valueFormat: 'yyyy-MM-dd'
        },
        {
          type: 'RANGE_DATE',
          label: '入库日期',
          fieldName: 'finishedDateBegin|finishedDateEnd',
          valueFormat: 'yyyy-MM-dd'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 200,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.showItems(props.row, 1)}>
                  明细
                </el-button>
                <el-button size="mini" type="text" disabled={props.row.orderStatus == 90311001 || props.row.orderStatus == 90311004 ? false : true} onClick={() => this.showItems(props.row, 2)}>
                  编辑
                </el-button>
                <el-button size="mini" type="text" onClick={() => this.showLogs(props.row)}>
                  审核日志
                </el-button>
              </div>
            );
          }
        },
        {
          title: '调拨单号',
          dataIndex: 'allocateInNo',
          sorter: true,
          filter: false,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '调拨单状态',
          dataIndex: 'orderStatus',
          sorter: true,
          filter: false,
          filterType: 'checkbox',
          filterItems: this.statusList,
          dictItems: this.statusList,
          showOverflowTooltip: true
        },
        {
          title: '原调拨单号',
          dataIndex: 'oldAllocateOutNo',
          sorter: true,
          filter: false,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '对方经销商代码',
          dataIndex: 'customerCode',
          sorter: true,
          filter: false,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '对方经销商名称',
          dataIndex: 'customerName',
          sorter: true,
          filter: false,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '调拨总数量',
          dataIndex: 'inQuantity',
          sorter: true,
          filter: false,
          filterType: 'number',
          precision: 2,
          showOverflowTooltip: true
        },
        {
          title: '调拨总金额',
          dataIndex: 'inAmount',
          sorter: true,
          filter: false,
          filterType: 'number',
          precision: 2,
          showOverflowTooltip: true
        },
        {
          title: '创建日期',
          dataIndex: 'createdAt',
          sorter: true,
          filter: false,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd',
          showOverflowTooltip: true
        },
        {
          title: '申请备注',
          dataIndex: 'remark',
          sorter: true,
          filter: false,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '审核日期',
          dataIndex: 'examinedDate',
          sorter: true,
          filter: false,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd',
          showOverflowTooltip: true
        },
        {
          title: '审核意见',
          dataIndex: 'examinedRemark',
          sorter: true,
          filter: false,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '入库日期',
          dataIndex: 'finishedDate',
          sorter: true,
          filter: false,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd',
          showOverflowTooltip: true
        }
      ];
    },
    collapseHandle() {
      this.refs.table.EXECUTE_RESET_HEIGHT();
    },
    async showItems(row, flag) {
      if (flag == 1) {
        console.log('row::', row);
        let res = await queryAllocationIn({ allocateInNo: row.allocateInNo });
        // jsonToHump(res.data.rows[0]);
        console.log('res::', res);
        this.itemsData = res.data.rows[0];
        this.visible1 = true;
      } else {
        console.log('row::', row);
        let res = await queryAllocationIn({ allocateInNo: row.allocateInNo });
        // jsonToHump(res.data.rows[0]);
        console.log('res::', res);
        this.itemsData1 = res.data.rows[0];
        this.visible2 = true;
      }
    },
    async showLogs(row) {
      let res = await getExaminedLogs({ allocateInNo: row.allocateInNo });
      if (res.resultCode == 200) {
        this.logData = res.data;
        this.showPanel2 = true;
      } else {
        this.$notify.error({ title: '提示信息', message: '获取日志失败' });
      }
    },
    async confirm(val) {
      console.log('confirm::', val);
      let res = await saveAllocationIn(val);
      if (res.resultCode == '200') {
        this.$notify({
          title: '提示',
          message: '保存成功',
          type: 'success'
        });
      }
      let val1 = await this.$refs.topFilter.GET_FORM_DATA();
      this.fetchParams = Object.assign({}, val1);
    },
    // 点击搜索
    async handleSearch(val) {
      this.fetchParams = Object.assign({}, val);
    },
    // 同步table数据
    handleSyncTableData(list) {
      this.syncTableData = list;
    },
    // 打印入库单
    async handleDayin() {
      if (Object.keys(this.selectList).length == 0) {
        this.$notify.error({ title: '提示信息', message: '请选中数据' });
        return;
      }
      // console.log(this.printdataList, 'this.printdataList');
      if (this.selectList.orderStatus != '90311006') {
        this.$notify.warning({ title: '提示信息', message: '只有已完成的单据可以打印' });
        return;
      }
      this.dy = true;
      let printParams = '';
      // 获取打印参数
      // try {
      //   printParams = await queryPartinventoryPrintParam();
      // } catch (err) {
      //   console.log('获取入库打印参数失败', err);
      // }
      const res = await printData(this.selectList.partAllocateInId, printParams ? printParams.data[0].bParaValue : 0);
      this.allInprintList = res.data;
      console.log(this.allInprintList, 'this.allInprintList');
      // this.allInprintList.baseInfo.STOCK_IN_TYPE = '调拨入库-' + this.createDictText(this.SalesprintList.baseInfo.STOCK_IN_TYPE, '8088'); // 修改出入库类型为采购入库
      // this.SalesprintList.baseInfo.STOCK_IN_TYPE = ;
      // this.allInprintList.baseInfo.FINISHED_TYPE = '入库时间'; // 修改领料时间为->入库时间
      this.cunUserList.forEach(x => {
        if (this.allInprintList.baseInfo.USER_ID == x.userId) {
          this.allInprintList.baseInfo.USER_NAME = x.employeeName;
        }
        if (this.allInprintList.baseInfo.CREATED_BY == x.userId) {
          this.allInprintList.baseInfo.CREATED_NAME = x.employeeName;
        }
      });
      // this.SalesprintList.baseInfo.USER_ID
      // 打印
      this.$nextTick(() => {
        this.$refs.allInprint.EXCUTE_PRINT();
      });
    }
  }
};
</script>

<style scoped></style>
